﻿
using IdentityModel;
using IdentityModel.Client;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Models.Common;
using Models.Identity;
using Models.JsonResultModel;
using Models.WebClient;
using SqlSugar;
using System;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Net.Http.Headers;
using System.Security.Principal;
using UtilsBase;
using UtilsORM.MySqlData;
using UtilsORM.MySqlData;
using ServiceWeb.APIRequest;
using ServiceWeb.DBGateway;
using UtilsORM;
using UtilsORM.MySqlData;
using GatewayServer.Controllers.API.Common;
using GatewayServer.Controllers.API.Models;
namespace GatewayServer.Controllers.API.Mobile
{
    [Route("api/mobile/[controller]/[action]")]
    [ApiController]
    public class DeviceController : ApiCommonControllerBase
    {

        /// <summary>
        /// 设备控制
        /// </summary>
        /// <param name="dguid"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        /// 
       
        public RespResultData sendDeviceControl(string dguid, string key)
        {
            iot_device device = new DBIotDevice().getDevice(dguid);
            bool isOnline = new DBIotDeviceLiveStateCache().getGateWayIsOnline(device.d_gw_d_guid);
            if (isOnline == false)
            {
                return RespResult.Faild("失败，网关离线");
            }
            new ServiceDeviceControl().sendDeviceCommand(dguid, key, "移动端-指令发送");
            return RespResult.Sucess();
        }


        /// <summary>
        /// 获取设备
        /// </summary>
        /// <param name="dguid"></param>
        /// <returns></returns>
        /// 
       
        public RespResultData getDevice(string dguid)
        {
            return RespResult.Sucess(new DBIotDevice().getDevice(dguid));
        }
       
        public RespResultData getClientCommandDeviceByList()
        {
            string cguid = baseClientLoginUserInfo.cGuid;
            return RespResult.Sucess(new DBIotDevice().getClientCommandDeviceByList(cguid));
        }

        /// <summary>
        /// 继电器列表
        /// </summary>
        /// <param name="p_guid"></param>
        /// <returns></returns>
        /// 
       
        public RespResultData getRelayList(string p_guid = null)
        {
            // Console.WriteLine("getRelayList1" + p_guid+DateTime.Now.ToString());
            string sql = "select d.d_name,d.d_guid,d.d_code,a.ls_response_state,gwd.d_code gw_code,a.ls_live_state,case when b.ls_live_state_set_time  is not null  and b.ls_live_state_set_time>date_add('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',interval -2 minute) then '在线' else '离线' end onlinestate, case when  a.ls_live_state is null then '状态异常' when a.ls_live_state=3 then '检测中' when  a.ls_live_state=0 then '待检测' when " +
                "                  a.ls_live_state = 2 then '状态异常'  end dlivestate,( case when vc_value = 'open' then '打开' when vc_value = 'close' then '关闭' end ) dvalue from  iot_device_gateway inner join iot_device d on d_gw_d_guid = gw_d_guid  inner join iot_device_model on d_model_guid = m_guid  inner join iot_device_model_type on m_type_guid = t_guid  left join iot_device_live_state a on a.ls_d_guid = d_guid left join iot_device_live_state b on b.ls_d_guid = gw_d_guid  inner join iot_device gwd on gwd.d_guid = gw_d_guid left join iot_device_value_current on vc_d_guid = d.d_guid " +
                  " where d.d_status=0 and  t_code in('1004','1007')  ";
            if (!string.IsNullOrEmpty(p_guid))
            {
                sql = sql + " and d.d_p_guid='" + p_guid + "'";
            }
            // sql = sql + " and d.d_c_guid='" + baseClientLoginUserInfo.cGuid + "' ";
            sql = sql + "  order by d.d_order asc";
            DataTable dt = MySqlYihongIot.GetDataTable(sql);
            //  Console.WriteLine("getRelayList2" + sql + DateTime.Now.ToString());
            return RespResult.Sucess(dt);
        }
        /// <summary>
        /// 传感器列表
        /// </summary>
        /// <param name="p_guid"></param>
        /// <returns></returns>
        /// 
       
        public RespResultData getSensorList(string p_guid = null)
        {
            EFYihongIotContext ef = new EFYihongIotContext();
            string sql = "select d.d_name,d.d_guid,d.d_gw_d_guid,d.d_code,gwd.d_code gatewaycode, (case when gw_live_time>date_add('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',interval -2 minute) then '在线' else '离线' end) as onlinestate from iot_device d  inner join iot_device_gateway on d_gw_d_guid=gw_d_guid inner join iot_device_model on d_model_guid=m_guid  inner join iot_device_model_type on m_type_guid=t_guid inner join iot_device gwd on gwd.d_guid=gw_d_guid left join iot_device_live_state on ls_d_guid=d.d_guid  where t_code='1001'  and d.d_status=0 ";
            if (!string.IsNullOrEmpty(p_guid))
            {
                sql = sql + " and d.d_p_guid='" + p_guid + "'";
            }
            // sql = sql + " and d.d_c_guid='" + baseClientLoginUserInfo.cGuid + "' ";
            sql = sql + "  order by d.d_order asc";
            DataTable dt = MySqlYihongIot.GetDataTable(sql);
            List<ViewDeviceVariable> viewDeviceVariables = new List<ViewDeviceVariable>();
            ViewDeviceVariable viewDevice = new ViewDeviceVariable();
            foreach (DataRow row in dt.Rows)
            {
                viewDevice = new ViewDeviceVariable();
                viewDevice.d_name = row["d_name"].ToString();
                viewDevice.d_code = row["d_code"].ToString();
                viewDevice.d_guid = row["d_guid"].ToString();
                viewDevice.onlinestate = row["onlinestate"].ToString();
                viewDevice.gateway = ef.iot_device_gateway.Where(c => c.gw_d_guid == row["d_gw_d_guid"]).FirstOrDefault();
                List<iot_device_value_current> currents = ef.iot_device_value_current.Where(c => c.vc_d_guid == row["d_guid"]).ToList();
                List<ViewDeviceValueCurrent> viewDeviceValueCurrents = new List<ViewDeviceValueCurrent>();
                foreach (iot_device_value_current value_Current in currents)
                {
                    ViewDeviceValueCurrent deviceValueCurrent = new UtilsClassClone().CloneByReflection<iot_device_value_current, ViewDeviceValueCurrent>(value_Current);
                    iot_device_model_variable variable = ef.iot_device_model_variable.Where(c => c.v_key == deviceValueCurrent.vc_key).FirstOrDefault();
                    if (variable != null)
                    {
                        deviceValueCurrent.unit = variable.v_unit;
                    }
                    viewDeviceValueCurrents.Add(deviceValueCurrent);
                }


                viewDevice.deviceValues = viewDeviceValueCurrents;
                viewDeviceVariables.Add(viewDevice);
            }
            return RespResult.Sucess(viewDeviceVariables);
        }
        /// <summary>
        /// 网关列表
        /// </summary>
        /// <param name="p_guid"></param>
        /// <returns></returns>
        /// 
       
        public RespResultData getGateWayList(string p_guid = null)
        {
            string sql = "select d_name,d_guid,d_code,gw_code,(case when gw_local_ip is null or gw_local_ip='' then '待连网' else gw_local_ip end) ip,case when ls_live_state_set_time>date_add('" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "',interval -2 minute) then '主机在线' else '主机离线' end onlinestate " +
                               "   from   iot_device_gateway a join iot_device d on d.d_guid=gw_d_guid  left join iot_device_live_state on ls_d_guid=d_guid   " +
                               " where d.d_status=0 ";


            if (!string.IsNullOrEmpty(p_guid))
            {
                sql = sql + " and d.d_p_guid='" + p_guid + "'";
            }
            // sql = sql + " and d.d_c_guid='" + baseClientLoginUserInfo.cGuid + "' ";
            sql = sql + "  order by d.d_order asc";
            DataTable dt = MySqlYihongIot.GetDataTable(sql);
            return RespResult.Sucess(dt);
        }
    }
}
